import { Address } from '../../utils/address.js';
import {Order} from '../order/order-model.js';
import {My} from 'my-model.js';

var address = new Address();
var order = new Order();
var my = new My();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageIndex:1,
    orderArr:[],
    isLoadedAll:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this._loadData();
    this._getAddressInfo();
  },

  onShow:function(){
    var newOrderFlag = order.hasNewOrder();
    if (newOrderFlag){      
      this.refresh();
    }
  },

  refresh:function(){
    var that = this;
    this.data.orderArr = []; //订单初始化
    this._getOrders(()=>{
      that.data.isLoadedAll = false; //是否加载完全
      that.data.pageIndex = 1;
      order.execSetStorageSync(false);
    });
  },

  editAddress: function (event) {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        var addressInfo = {
          name: res.userName,
          mobile: res.telNumber,
          totalDetail: address.setAddressInfo(res)
        }
        that._bindAddressInfo(addressInfo);

        //保存地址
        address.submitAddress(res, (flag) => {
          if (!flag) {
            that.showTips('操作提示', '地址信息更新失败!');
          }
        });
      }
    })
  },

  _getAddressInfo:function(){
    address.getAddress((addressInfo)=>{
      this._bindAddressInfo(addressInfo);
    });
  },

  /**绑定地址信息 */
  _bindAddressInfo: function (addressInfo){
    this.setData({
      addressInfo: addressInfo
    });
  },

  _loadData:function(){
      my.getUserInfo((data)=>{
        this.setData({
          userInfo : data
        });
      });

      this._getOrders();
  },

  _getOrders:function(callback){
    order.getOrders(this.data.pageIndex,(res)=>{
      var data = res;
      if (data.length>0){
        this.data.orderArr.push.apply(this.data.orderArr,data);
        this.setData({
          orderArr: this.data.orderArr
        });
      }
      else{
        this.data.isLoadedAll = false;
      }
      callback && callback();
    })
  },

  onReachBottom:function(){
    if (!this.data.isLoadedAll){
      this.data.pageIndex++;
      this._getOrders();
    }
  },

  /**显示订单具体信息 */
  showOrderDetailInfo:function(event){
    var id = order.getDataSet(event,'id');
    wx.navigateTo({
      url: '../order/order?from=order&id='+id,
    })
  }

})